package com.damai.action.impl;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.pay.PayAction;
import com.citywithincity.pay.PayFactory;
import com.citywithincity.utils.IoUtil;
import com.damai.action.BaseServiceAction;

public class ServerNotifyAction extends BaseServiceAction {
	public ServerNotifyAction(String key) {
		super(key);
	}

	private static final Log logger = LogFactory.getLog(ServerNotifyAction.class);
	private static final String SUCCESS = "success";
	private static final String FAIL = "fail";

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException {

		logger.info(request.getRequestURI());
		PrintWriter writer = null;
		try {
			// 解析
			writer = response.getWriter();
			if (handleServerNotify(request)) {
				logger.info(SUCCESS);
				writer.write(SUCCESS);
			} else {
				logger.info(FAIL);
				writer.write(FAIL);
			}
		} catch (IOException e) {
			logger.info(FAIL, e);
			if (writer != null) {
				writer.write(FAIL);
			}
		} finally {
			IoUtil.close(writer);
		}

	}

	private boolean handleServerNotify(HttpServletRequest request) throws IOException {
		String strType = (String) request.getAttribute("0");
		if (strType == null) {
			logger.error("type is null");
			return true;
		} else {
			//这个时候为
			String[] args = strType.split("-");
			if(args.length<2 || args.length>3){
				logger.error("Arg length is not 2 or 3!");
				return true;
			}
			int businessId = Integer.parseInt(args[0]);
			int type = Integer.parseInt(args[1]);
			String channel = null;
			if(args.length==3){
				channel = args[2];
			}
			PayAction<?, ?, ?> action = PayFactory.getPayAction(businessId);
			if(action==null){
				logger.error("Action not found!");
				return true;
			}
			return action.handleServerNotify(type, businessId, channel, request);
		}

	}

}
